package com.dfxs.config;

import com.dfxs.io.Resources;
import com.dfxs.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author zhangdongsheng
 * @version 1.0
 * @describe 读取sqlMapConfig配置文件
 * @date 2020/9/25 23:49
 */
public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 解析sqlMapConfig.xml文件封装到Configuration对象中
     * @param inputStream
     * @return
     */
    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
        //读取配置文件为Document对象
        Document document = new SAXReader().read(inputStream);
        //获取根节点
        Element rootElement = document.getRootElement();
        //获取property标签属性内容
        List<Element> propertyList = rootElement.selectNodes("//property");
        //创建Properties对象,存储数据库属性信息
        Properties properties = new Properties();
        for (Element property: propertyList) {
            String name = property.attributeValue("name");
            String value = property.attributeValue("value");
            properties.setProperty(name,value);
        }

        //将数据库连接信息封装到 c3p0 连接池ComboPooledDataSource对象中
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        //将数据库连接信息封装到Configuration对象中
        configuration.setDataSource(comboPooledDataSource);

        //mapper.xml解析: 拿到路径--字节输入流---dom4j进行解析
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for (Element mapper:mapperList) {
            String resource = mapper.attributeValue("resource");
            InputStream resourcesAsStream = Resources.getResourceAsStream(resource);
            XmlMapperBuilder xmlMapperBuilder = new XmlMapperBuilder(configuration);
            xmlMapperBuilder.parseMapper(resourcesAsStream);
        }


        return configuration;
    }
}
